package com.xzx.flink.streamapi.sink;

import com.xzx.flink.bean.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * @author xinzhixuan
 * @version 1.0
 * @date 2021-08-29 10:41 下午
 */
public class Sink_06_CustomJDBC {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> streamSource = env.readTextFile("/Users/xinzhixuan/work/git/flink-study-java/src/main/resources/sensor.txt");
        SingleOutputStreamOperator<SensorReading> map = streamSource.map(new MapFunction<String, SensorReading>() {
            @Override
            public SensorReading map(String value) throws Exception {
                String[] split = value.split(" ");
                return new SensorReading(split[0], Long.parseLong(split[1]), Double.parseDouble(split[2]));
            }
        });
        map.print();

        map.addSink(new RichSinkFunction<SensorReading>() {
            Connection conn = null;
            PreparedStatement insertStmt = null;
            PreparedStatement updateStmt = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/flink", "root", "12345678");
                insertStmt = conn.prepareStatement("insert into sensor (id, ts, temperature) values (?,?,?)");
                updateStmt = conn.prepareStatement("update sensor set ts=?, temperature=? where id =?");
            }

            @Override
            public void close() throws Exception {
                insertStmt.close();
                updateStmt.close();
                conn.close();
            }

            @Override
            public void invoke(SensorReading value, Context context) throws Exception {
                updateStmt.setLong(1, value.getTimestamp());
                updateStmt.setDouble(2, value.getTemperature());
                updateStmt.setString(3, value.getId());
                updateStmt.execute();
                if (updateStmt.getUpdateCount() == 0) {// 没有更新成功就插入
                    insertStmt.setString(1, value.getId());
                    insertStmt.setLong(2, value.getTimestamp());
                    insertStmt.setDouble(3, value.getTemperature());
                    insertStmt.execute();
                }
            }
        });

        env.execute(Sink_06_CustomHBase.class.getName());
    }
}
